<script setup lang="ts">
import { ref, onBeforeMount, watch, onMounted, defineProps } from "vue";
import ReCol from "@/components/ReCol";
import { formRules } from "./utils/rule";
import { message } from "@/utils/message";
import { formProps, type FormInstance } from "element-plus";
import AddCoordinate from "@/components/AddCoordinate/index.vue";
import { useMapStoreHook } from "@/store/modules/map";
import { GetAllStation } from '@/utils/api/dispatch/station'
import { GetByName } from '@/utils/api/dispatch/station'
import { PureTableBar } from "@/components/RePureTableBar";
import { useCrossDept } from "./utils/crossHook";
import { getCross, updateCross, addCross } from '@/utils/api/dispatch/cross'
import { cloneDeep } from "lodash";
import Konva from "konva";
import { useDept } from "./utils/hook";
import { cross, stage, layer, getCross1 } from "@/views/home/components/dxfMap";
import { ElMessageBox } from 'element-plus'
import { delCross } from '@/utils/api/dispatch/cross'

const pureMap = useMapStoreHook()

interface Props {
    formInline?: any,
    isUpdate?: boolean
}

// 定义组件的属性（props）并设置默认值
const props = withDefaults(defineProps<Props>(), {
    // 定义一个名为 isUpdate 的属性，并设置其默认值为 false
    isUpdate: false
});

const ruleFormRef = ref();
const newFormInline: { [key: string]: any; } = ref({
    name: pureMap.incrementalName ? `${Number(pureMap.incrementalName) + 1}` : '',
    status: 1,
    stationList: [{}],
    note: "",
    type: 1,
    stationids: null,
    parallestaids: null,
});

// watch(() => pureMap.incrementalName, (val) => {
//     // console.log('watch中的=>', val);
//     newFormInline.value.name = `${Number(val) + 1}`
//     // console.log('watch中的newFormInline=>', newFormInline.value.name);


// })

const isUpdate = ref(props.isUpdate);
const stationOptions = ref([]);// 全部站点列表
const {
    columns,
    loading,
    dataList,
    onSearch,
    pagination,
} = useCrossDept();

function getRef() {
    return ruleFormRef.value;
}

function crossNameChange(val) {
    pureMap.$patch((state) => {
        state.crossDetail.name = val
    })
}

function chores(title, data?) {
    // console.log(pureMap.incrementalName);
    // if (title === "新增") {
    //     pureMap.changeName(data.name)
    // }

    // if (title === "新增") getCross1(data)
    // let id = new Date().getTime()
    // cross({ id, ...data }, data.type)
    // 新增的交管储存到pureMap.stageKonva里
    // pureMap.getStage(stage);
    // 显示一个成功消息提示，消息内容为 `${title}成功`，消息类型为 "success"
    message(`${title}成功`, {
        type: "success"
    });
    // 调用 pureMap.targetCross 对象的 name 方法，设置其名称为 `cross-${pureMap.crossDetail.name}`
    pureMap.targetCross?.name(`cross-${pureMap.crossDetail.name}`)
    // 以下代码被注释掉了，原本是用来设置 pureMap.targetCross 对象的 attrs 属性中的 type 为 1
    // pureMap.targetCross.attrs.type = data.type
    // 调用 onSearch 函数，可能是用于重新搜索或刷新数据
    onSearch()
    // 使用 pureMap.$patch 方法更新 pureMap 对象的状态，将 crossSwitch 属性设置为 false
    pureMap.$patch({
        crossSwitch: false
    })
    // 将 isUpdate 的值设置为 false，表示当前不是更新状态
    isUpdate.value = false
    // 调用 resetForm 函数，传入 ruleFormRef.value 作为参数，用于重置表单
    resetForm(ruleFormRef.value)
    // layer.draw();
}

/**
 * 新增或修改时都需要给地图上所选中的交管数据添加一个交管状态
 * 新增：1
*/
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            var data = newFormInline.value
            // console.log('提交的数据', data);
            // data.name.toString()
            data.stationids = newFormInline.value?.stationids?.toString()
            data.parallestaids = newFormInline.value?.parallestaids?.toString()
            if (isUpdate.value) {
                updateCross(data).then(res => {
                    if (res.Code === 0) chores('修改')
                    // pureMap.targetCross.children.forEach(v=>{
                    //   if(v.name() === 'circle'){
                    //     v.fill('red')
                    //   }else{
                    //     v.stroke('red')
                    //   }
                    // })
                })
            } else {
                addCross(data).then(res => {
                    if (res.Code === 0) {
                        chores('新增', data)
                    }
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 重置
const resetForm = (formEl: FormInstance | undefined) => {
    // 检查表单元素是否存在，如果不存在则直接返回
    if (!formEl) return
    // 重置表单字段
    formEl.resetFields()
    newFormInline.value.name = `${Number(pureMap.incrementalName) + 1}`
    // 关联form与pureMap
    connect()
    // 将isUpdate的值设置为false，表示当前不是更新状态
    isUpdate.value = false

    // 检查isUpdate的值是否为true，如果是则执行以下操作
    if (isUpdate.value) {
        // 销毁pureMap中的targetCross对象
        pureMap.targetCross.destroy()

        // 遍历pureMap.targetCross的子元素
        pureMap.targetCross.children.forEach(v => {
            // 如果子元素的名称是'circle'，则将其填充颜色设置为红色
            if (v.name() === 'circle') {
                v.fill('red')
            } else {
                // 否则，将子元素的描边颜色设置为红色
                v.stroke('red')
            }
        })
    }
}

// 编辑
async function crossUpdate(id: number) {
    // 获取跨站信息
    let { Content } = await getCross(id)
    // 将跨站信息赋值给newFormInline
    newFormInline.value = Content

    // 将stationids字段转换为数字数组
    if (newFormInline.value.stationids) {
        newFormInline.value.stationids = newFormInline.value?.stationids?.split(',').map(v => { return Number(v) })
    } else {
        newFormInline.value.stationids = null
    }
    if (newFormInline.value.parallestaids) {
        newFormInline.value.parallestaids = newFormInline.value?.parallestaids?.split(',').map(v => { return Number(v) })
    } else {
        newFormInline.value.parallestaids = null
    }
    // 遍历pureMap.crossDetail，将Content中的值赋值给pureMap.crossDetail
    for (let key in pureMap.crossDetail) {
        pureMap.$patch((state) => { // 使用$patch方法更新state
            state.crossDetail[key] = Content[key]
        })
    }
    // 设置isUpdate为true
    isUpdate.value = true

    pureMap.getCross(pureMap.stageKonva.find(`.cross-${pureMap.crossDetail.name}`)[0])
}

// 删除交管
function deleteCross(formEl) {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            var data = newFormInline.value
            data.stationids = newFormInline.value?.stationids?.toString()
            if (isUpdate.value) {
                ElMessageBox.confirm(
                    `是否确认删除名称为${data.name}的数据项?`,
                    '提示',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning',
                        center: true
                    }
                ).then(() => {
                    delCross(data.id).then(res => {
                        if (res.Code === 0) {
                            pureMap.stageKonva.find(`.cross-${data.name}`)[0].destroy()
                            chores('删除', data)
                        }
                    })
                }).catch(() => { })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 关联form与pureMap
function connect() {
    // 遍历 pureMap.crossDetail 对象的所有键
    Object.keys(pureMap.crossDetail).forEach(v => {
        // 使用 $patch 方法对 pureMap 的状态进行局部更新
        pureMap.$patch((state) => {
            // 将 newFormInline.value 中对应键的值赋给 pureMap.crossDetail 中对应的键
            state.crossDetail[v] = newFormInline.value[v]
        })
    })
}

// 表单站点名称
const stationName = ref(null)
// 表单站点合集
let setList = new Set()
let stationNameList = ref()
// 失去焦点时触发
const crossStationName = () => {
    let arr = stationName.value.split('，').map(String);
    // // 遍历 stationOptions 数组中的每一个元素
    // stationOptions.value.forEach(item => {
    //     // 检查 arr 数组中是否包含当前元素的 name 属性
    //     if (arr.includes(item.stationname)) {
    //         // 如果包含，则将当前元素的 name 属性添加到 setList 数组中
    //         setList.add(item.stationname)
    //     }
    // })
    arr.forEach(item => {
        GetByName({ stationName: item }).then(res => {
            if (res.Content) {
                setList.add(item)
            } else {
                message(`${item}站点不存在`, {
                    type: "error"
                });
            }
        })
    });
    stationNameList.value = [...setList]
}

// 监听抽屉状态，抽屉关闭清空站点数据
watch(() => pureMap.crossSwitch, (val) => {
    if (!val) {
        stationName.value = null
        setList.clear()
    }
})


onMounted(async () => {
    // 站点下拉
    const { Content } = await GetAllStation()
    stationOptions.value = Content
    connect()
    // console.log('名称=>', incrementalName.value);

})


defineExpose({ getRef, crossUpdate, resetForm });
</script>

<template>
    <el-form ref="ruleFormRef" :model="newFormInline" :rules="formRules" label-width="50px">
        <el-row :gutter="30">
            <re-col :value="12" :xs="24" :sm="24">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="newFormInline.name" size="small" clearable placeholder="请输入名称"
                        @change="crossNameChange" />
                </el-form-item>
            </re-col>
            <re-col :value="12" :xs="24" :sm="24">
                <el-form-item label="类型" prop="type">
                    <el-select v-model="newFormInline.type" size="small" placeholder="请选择交管类型" style="width:100%">
                        <!-- <el-option label="站点交管" :value="0" /> -->
                        <el-option label="唯一区域交管" :value="1" />
                        <el-option label="巷道区域交管" :value="2" />
                        <el-option label="公共区域交管" :value="3" />
                        <el-option label="可穿行交管" :value="4" />
                        <el-option label="巷道多车交管" :value="5" />
                    </el-select>
                </el-form-item>
            </re-col>
            <re-col :value="12" :xs="24" :sm="24">
                <el-form-item label="状态" prop="status">
                    <el-select v-model="newFormInline.status" size="small" placeholder="请选择状态" style="width:100%">
                        <el-option label="启用" :value="1" />
                        <el-option label="禁用" :value="0" />
                        <el-option label="锁定" :value="2" />
                    </el-select>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24" v-if="newFormInline.type === 4">
                <el-form-item label="穿行站点" prop="stationids" label-width="80px">
                    <el-select v-model="newFormInline.stationids" multiple placeholder="请选择站点集合" filterable
                        style="width:100%">
                        <el-option v-for="item in stationOptions" :key="item.stationid" :label="item.stationname"
                            :value="item.stationid" />
                    </el-select>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24" v-if="newFormInline.type === 4">
                <el-form-item label="并行站点" prop="parallestaids" label-width="80px">
                    <el-select v-model="newFormInline.parallestaids" multiple placeholder="请选择站点集合" filterable
                        style="width:100%">
                        <el-option v-for="item in stationOptions" :key="item.stationid" :label="item.stationname"
                            :value="item.stationid" />
                    </el-select>
                </el-form-item>
            </re-col>
            <!-- <re-col :value="24" :xs="24" :sm="24" v-show="!newFormInline.type">
                <el-form-item label="站点集合" prop="stationids" label-width="70px">
                    <el-select v-model="newFormInline.stationids" size="small" multiple placeholder="请选择站点集合"
                        style="width:100%">
                        <el-option v-for="item in stationOptions" :key="item.stationid" :label="item.stationname"
                            :value="item.stationid" />
                    </el-select>
                </el-form-item>
            </re-col> -->

            <!-- <re-col :value="24" :xs="24" :sm="24">
                <el-form-item label="站点" prop="stationName">
                    <el-input v-model="stationName" size="small" clearable placeholder="请输入包含的站点，多个之间用逗号隔开"
                        type="textarea" @blur="crossStationName" />
                    <div :class="{ stationArr: true }">
                        <el-tag size="small" type="success" v-for="v in stationNameList" :key="v"
                            style="margin:5px 5px;">
                            {{ v }}
                        </el-tag>
                    </div>
                </el-form-item>
            </re-col> -->
            <re-col :value="24" :xs="24" :sm="24" v-show="newFormInline.type">
                <el-form-item label="区域" prop="stationList" style="font-weight: 700;">
                    <Add-coordinate :data="newFormInline.stationList"></Add-coordinate>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24">
                <el-form-item label="备注" prop="note">
                    <el-input v-model="newFormInline.note" size="small" clearable placeholder="请输入备注" type="textarea" />
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24">
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                    <el-button type="danger" @click="resetForm(ruleFormRef)">清空数据</el-button>
                    <el-button type="danger" @click="deleteCross(ruleFormRef)" v-show="isUpdate">删除</el-button>
                </el-form-item>
            </re-col>
        </el-row>
    </el-form>

    <!-- <PureTableBar title="交管列表" :columns="columns" size="small" @refresh="onSearch">
      <template v-slot="{ size, dynamicColumns }">
        <pure-table ref="tableRef" adaptive align-whole="center" row-key="Id" showOverflowTooltip table-layout="auto"
          :loading="loading" :size="size" :data="dataList" :columns="dynamicColumns" :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false" :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }">
          <template #operation="{ row }">
            <el-button class="reset-margin" :size="size" link type="primary" @click="crossUpdate(row.id)">
              编辑
            </el-button>
          </template>
</pure-table>
</template>
</PureTableBar> -->
</template>

<style lang="scss" scoped>
.el-radio {
    margin-right: 16px;
}
</style>
